package com.huimei.hmc.upms.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huimei.hmc.common.exception.BizException;
import com.huimei.hmc.upms.sys.api.IUpmsUserService;
import com.huimei.hmc.upms.sys.dao.mapper.*;
import com.huimei.hmc.upms.sys.pojo.enums.upmsuser.UpmsUserEmployeeAttrEnums;
import com.huimei.hmc.upms.sys.pojo.model.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Huangyuheng on 2017/7/5.
 */
@Service
public class UpmsUserServiceImpl implements IUpmsUserService {

    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    private String algorithmName = "md5";
    private int hashIterations = 2;

    @Autowired
    private UpmsUserMapper upmsUserMapper;

    @Autowired
    private UpmsUserRoleMapper upmsUserRoleMapper;

    @Autowired
    private UpmsRoleResourceMapper upmsRoleResourceMapper;

    @Autowired
    private UpmsResourceMapper upmsResourceMapper;

    @Autowired
    private UpmsRoleMapper upmsRoleMapper;


    /**
     * 保存用户
     *
     * @param upmsUser
     * @return
     * @author huangyuheng 20170717
     */
    @Override
    public int saveUpmsUser(UpmsUser upmsUser) {

        UpmsUser upmsUserTmp = upmsUserMapper.selectByUsername(upmsUser.getUsername());
        if (null != upmsUserTmp) {
            throw new BizException("登录名已存在");
        }

        //加盐
        upmsUser.setSalt(randomNumberGenerator.nextBytes().toHex());
        //新密码
        String newPassword = new SimpleHash(
                algorithmName,
                upmsUser.getPassword(),
                ByteSource.Util.bytes(upmsUser.getSalt()),
                hashIterations).toHex();

        upmsUser.setPassword(newPassword);

        return upmsUserMapper.insertSelective(upmsUser);
    }

    /**
     * 更新用户信息
     *
     * @param upmsUser
     * @return
     * @author huangyuheng 20170717
     */
    @Override
    public int updateUpmsUser(UpmsUser upmsUser) {
        return upmsUserMapper.updateByPrimaryKeySelective(upmsUser);
    }

    /**
     * 根据id获取用户信息
     *
     * @param id
     * @return
     * @author huangyuheng 20170717
     */
    @Override
    public UpmsUser getUpmsUserById(Long id) {
        return upmsUserMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据id删除用户信息
     *
     * @param id
     * @return
     * @author huangyuheng 20170717
     */
    @Override
    public int removeUpmsUserById(Long id) {
        return upmsUserMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据用户名获取用户信息
     *
     * @param username
     * @return
     * @author huangyuheng 20170717
     */
    @Override
    public UpmsUser getUpmsUserByUsername(String username) {
        return upmsUserMapper.selectByUsername(username);
    }

    /**
     * 修改用户密码
     *
     * @param id
     * @param oldPassword
     * @param password
     * @param rePassword
     * @author huangyuheng 20170717
     */
    @Override
    public void changeUserPassword(Long id, String oldPassword, String password, String rePassword) {
        UpmsUser upmsUserTmp = upmsUserMapper.selectByPrimaryKey(id);

        if (null == upmsUserTmp) {
//            throw new UpmsException("该用户信息不存在");
        }

        //新密码
        String oldSaltPassword = new SimpleHash(
                algorithmName,
                oldPassword,
                ByteSource.Util.bytes(upmsUserTmp.getSalt()),
                hashIterations).toHex();

        if (!upmsUserTmp.getPassword().equals(oldSaltPassword)) {
//            throw new UpmsException("原密码输入错误");
        }

        if (!password.equals(rePassword)) {
//            throw new UpmsException("新密码和确认密码不符");
        }

        String newSalt = randomNumberGenerator.nextBytes().toHex();

        String newSaltPassword = new SimpleHash(
                algorithmName,
                password,
                ByteSource.Util.bytes(newSalt),
                hashIterations).toHex();

        UpmsUser upmsUser = new UpmsUser();
        upmsUser.setId(id);
        upmsUser.setSalt(newSalt);
        upmsUser.setPassword(newSaltPassword);
        upmsUser.setModifiedBy(upmsUserTmp.getUsername());
        upmsUser.setIsFirstLogin(false);

        upmsUserMapper.updateByPrimaryKeySelective(upmsUser);
    }

    /**
     * 获取用户角色id
     *
     * @param username
     * @return
     * @author huangyuheng 20170720
     */
    @Override
    public Set<String> getUpmsUserRoleCode(String username) {
        Set<String> roleIds = new HashSet<>();
        UpmsUser upmsUser = upmsUserMapper.selectByUsername(username);
        if (null != upmsUser) {
            List<UpmsUserRole> upmsUserRoleList = upmsUserRoleMapper.selectByUserId(upmsUser.getId());
            for (UpmsUserRole upmsUserRole : upmsUserRoleList) {
                UpmsRole upmsRole = upmsRoleMapper.selectByPrimaryKey(upmsUserRole.getRoleId());
                roleIds.add(upmsRole.getCode());
            }
        }

        return roleIds;
    }

    /**
     * 获取用户权限
     *
     * @param username
     * @return
     * @author huangyuheng 20170720
     */
    @Override
    public Set<String> getUpmsUserPermission(String username) {
        Set<String> permissionNames = new HashSet<>();
        UpmsUser upmsUser = upmsUserMapper.selectByUsername(username);
        if (null != upmsUser) {

            //获取用户角色的权限
            List<UpmsUserRole> upmsUserRoleList = upmsUserRoleMapper.selectByUserId(upmsUser.getId());
            for (UpmsUserRole upmsUserRole : upmsUserRoleList) {
                List<UpmsRoleResource> upmsRoleResourceList = upmsRoleResourceMapper.selectByRoleId(upmsUserRole.getRoleId());
                for (UpmsRoleResource upmsRoleResource : upmsRoleResourceList) {
                    UpmsResource upmsResource = upmsResourceMapper.selectByPrimaryKey(upmsRoleResource.getResourceId());
                    if (null != upmsResource && StringUtils.isNotEmpty(upmsResource.getPermission())) {
                        permissionNames.add(upmsResource.getPermission());
                    }
                }
            }

//                //获取用户单独的权限
//                List<UpmsUserResource> upmsUserResourceList = upmsUserResourceMapper.selectByUserId(upmsUser.getId());
//                for (UpmsUserResource upmsUserResource : upmsUserResourceList) {
//                    UpmsResource upmsResource = upmsResourceMapper.selectByPrimaryKey(upmsUserResource.getResourceId());
//                    if (null != upmsResource && StringUtils.isNotEmpty(upmsResource.getPermission())) {
//                        permissionNames.add(upmsResource.getPermission());
//                    }
//                }
        }

        return permissionNames;
    }

}
